package top.jnaw.jee.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class AppSendUtils {

  public static String connectURL(String dest_url, String commString) {
    String rec_string = "";
    URL url;
    HttpURLConnection urlconn = null;
    OutputStream out = null;
    BufferedReader rd = null;
    try {
      url = new URL(dest_url);
      urlconn = (HttpURLConnection) url.openConnection();
      urlconn.setReadTimeout(1000 * 30);
      //urlconn.setRequestProperty("content-type", "text/html;charset=UTF-8");
      urlconn.setRequestMethod("POST");
      urlconn.setDoInput(true);
      urlconn.setDoOutput(true);
      out = urlconn.getOutputStream();
      out.write(commString.getBytes(StandardCharsets.UTF_8));
      out.flush();
      out.close();
      rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
      StringBuffer sb = new StringBuffer();
      int ch;
      while ((ch = rd.read()) > -1) {
        sb.append((char) ch);
      }
      rec_string = sb.toString();
    } catch (Exception e) {
      Log.i(e.getMessage());
      return "";
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (urlconn != null) {
          urlconn.disconnect();
        }
        if (rd != null) {
          rd.close();
        }
      } catch (Exception e) {
        Log.i(e.getMessage());
      }
    }
    return rec_string;
  }
}
